package com.example.event.publisher;

import com.alibaba.fastjson2.JSON;
import com.example.event.BaseEvent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class EventPublisher {

    private RabbitTemplate rabbitTemplate;

    public void publish(String topic, String routingKey, BaseEvent.EventMessage<?> eventMessage, int delay) {
        try {
            String messageJson = JSON.toJSONString(eventMessage);
            log.info("发送MQ消息 topic:{} routingKey:{} message:{}", topic, routingKey, messageJson);

            if (delay > 0) {
                rabbitTemplate.convertAndSend(topic, routingKey, messageJson, message -> {
                    message.getMessageProperties().setHeader("x-delay", delay);
                    return message;
                });
            } else {
                rabbitTemplate.convertAndSend(topic, routingKey, messageJson);
            }

        } catch (Exception e) {
            log.error("发送MQ消息失败 topic:{} routingKey:{} message:{}", topic, routingKey, JSON.toJSONString(eventMessage), e);
            throw e;
        }
    }
}
